import { Injectable } from '@angular/core';
import {ConfigService} from './config.service';
import {HttpClient} from '@angular/common/http';
import { Storage } from '@ionic/storage';
import {Users} from '../model/Users';
@Injectable({
  providedIn: 'root'
})
export class AuthService {

  constructor(private config:ConfigService
  ,private http:HttpClient
  , private storage: Storage) { }

  private loginUrl=this.config.HOST+"/public/login";
  login(username:string,password:string){
    let parm={
      "username":username,
      "password":password

    }
    return this.http.post(this.loginUrl,parm).toPromise();
  }

  private refreshTokenUrl=this.config.HOST+"/auth/refreshToken";
  refreshToken(){
    // this.http.get(this.refreshTokenUrl).toPromise()
    //   .then((data:any)=>{
    //     if (data.msg=='ok'){
    //
    //       this.storage.set("TOKEN",data.token)
    //         .then(()=>{
    //           console.log("TOKEN成功更新");
    //         })
    //     }
    //   })
    let last:number= 0;
    let current:number=new Date().getTime();
    this.storage.get("FRESHTIME")
      .then((value:number)=>{
        // console.log("currenttime"+current);
        //  console.log("lastfreshtime"+value);
        if(current-value>(10*60*1000)){
          this.http.get(this.refreshTokenUrl).toPromise()
            .then((data:any)=>{
              if(data.msg=='ok'){
                this.storage.set("TOKEN",data.token)
                  .then(()=>{
                    console.log("令牌成功刷新");
                  })

                this.storage.set("FRESHTIME",current);

              }
            })
        }

      })

  }

  private getRoleUrl=this.config.HOST+"/auth/getRole";
  getRole(){
    return this.http.get(this.getRoleUrl).toPromise();
  }


  private registUrl=this.config.HOST+"/public/regist";
  regist(u:Users){
    return this.http.post(this.registUrl,u).toPromise();
  }

  private getMyUserInfoUrl=this.config.HOST+"/member/getMyUserInfo";
   getMyUserInfo(){
     return this.http.get(this.getMyUserInfoUrl).toPromise();
   }

   private setHeadUrl=this.config.HOST+"/member/setUserHead";
   setUserHead(path:string){
     let parm={
       "headimg":path
     }
     return this.http.post(this.setHeadUrl,parm).toPromise();
   }
   private setPassUrl=this.config.HOST+"/member/setUserPass";
  setpass(oldpass:string,
          newpass:string){
    let parm={
      "oldpass":oldpass,
      "newpass":newpass
    }
    return this.http.post(this.setPassUrl,parm).toPromise();

  }
}
